/**
 *  auth: Wayne
 *  function: 鉴权接口
 * */

const express = require('express'),
  router = express.Router(),
  auth = require("../model/auth"),
  roleauth = require("../model/roleauth");

//对所有的功能请求进行鉴权
router.all("/*", (req, res, next) => {
  JSON.stringify()
  let obj = {}
  let requesturl = req.originalUrl
  let params = {}
  let userrole = ''
  if (req.cookies.userinfo) {
    userrole = req.cookies.userinfo.utype
  }
  params.authurl = requesturl
  auth.findOne({
    where: params
  }).then(record => {
    if (record) {
      roleauth.findOne({
        order: "roleid ASC",
        where: {roleid: userrole, authid: record.authid}
      }).then(rolerecord => {
        if (rolerecord) {
          next()
        } else {
          obj.return = '-2'
          obj.code = '-2'
          obj.message = '对不起，您暂无权限执行该操作！'
          obj.data = []
          res.send(obj)
        }
      }).catch(err => {
        next()
      })
    } else {
      next()
    }
  }).catch(err => {
    next()
  });
});


module.exports = router;
